import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, useSearchParams } from 'react-router-dom';
import {
  Table,
  Button,
  Space,
  message,
  Card,
  Statistic,
  Row,
  Col,
  Tooltip
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  TeamOutlined,
  UserOutlined,
  SearchOutlined,
  ReloadOutlined,
  CloseOutlined,
  EyeOutlined
} from '@ant-design/icons';
import styles from './ClassManagement.module.css';

interface ClassItem {
  id: number;
  className: string;
  lecturer: string;
  counselor: string;
  department: string;
  classroom?: string;
  createdAt: string;
  updatedAt: string;
}

interface ClassFormData {
  className: string;
  lecturer: string;
  counselor: string;
  department: string;
  classroom?: string;
}

interface Pagination {
  current: number;
  pageSize: number;
  total: number;
  totalPages: number;
}

interface OptionsData {
  departments: string[];
  majors: string[];
  lecturers: string[];
  counselors: string[];
  grades: string[];
}

interface Student {
  id: number;
  name: string;
  studentId: string;
  gender: string;
  phone: string;
  className: string;
  college: string;
  status: string;
  [key: string]: any;
}

const ClassManagement: React.FC = () => {
  const { t } = useTranslation('class');
  const { t: tStudent } = useTranslation('student');
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [classes, setClasses] = useState<ClassItem[]>([]);
  const urlParamsInitialized = useRef(false);
  const [loading, setLoading] = useState(false);
  const [editingClass, setEditingClass] = useState<ClassItem | null>(null);
  
  // 原生表单状态（添加和编辑共用）
  const [modalVisible, setModalVisible] = useState(false);
  const [formData, setFormData] = useState<ClassFormData>({
    className: '',
    lecturer: '',
    counselor: '',
    department: '',
    classroom: ''
  });
  const [formErrors, setFormErrors] = useState<Partial<Record<keyof ClassFormData, string>>>({});
  
  const [pagination, setPagination] = useState<Pagination>({
    current: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0
  });
  
  const [searchFilters, setSearchFilters] = useState({
    className: '',
    department: ''
  });
  const [stats, setStats] = useState({
    totalClasses: 0,
    totalStudents: 0,
    activeClasses: 0,
    averageStudents: 0
  });
  const [options, setOptions] = useState<OptionsData>({
    departments: [],
    majors: [],
    lecturers: [],
    counselors: [],
    grades: []
  });
  const [classNames, setClassNames] = useState<string[]>([]);
  
  // 学生列表相关状态
  const [isStudentsModalVisible, setIsStudentsModalVisible] = useState(false);
  const [selectedClassStudents, setSelectedClassStudents] = useState<Student[]>([]);
  const [selectedClassName, setSelectedClassName] = useState<string>('');
  const [selectedDepartment, setSelectedDepartment] = useState<string>('');
  const [selectedCounselor, setSelectedCounselor] = useState<string>('');
  const [selectedLecturer, setSelectedLecturer] = useState<string>('');
  const [selectedClassroom, setSelectedClassroom] = useState<string>('');
  const [isLoadingStudents, setIsLoadingStudents] = useState(false);

  // Get Dropdown Options
  const fetchOptions = async () => {
    try {
      const response = await fetch('/api/classes/options');
      if (response.ok) {
        const result = await response.json();
        console.log('Options data received:', result);
        console.log('Lecturers from API:', result.lecturers);
        
        // 确保讲师列表存在且为数组
        setOptions({
          departments: result.departments || [],
          majors: result.majors || [],
          lecturers: Array.isArray(result.lecturers) ? result.lecturers : [],
          counselors: result.counselors || [],
          grades: result.grades || []
        });
      } else {
        const errorText = await response.text();
        console.error('Failed to get options data:', response.status, errorText);
        // 如果API失败，不设置默认值，保持空数组
        setOptions({
          departments: [],
          majors: [],
          lecturers: [],
          counselors: [],
          grades: []
        });
      }
    } catch (error) {
      console.error('Failed to get options data:', error);
      // 如果出错，不设置默认值，保持空数组
      setOptions({
        departments: [],
        majors: [],
        lecturers: [],
        counselors: [],
        grades: []
      });
    }
  };

  // Get Class List
  const fetchClasses = async (page = 1, pageSize = 10, filters?: { className?: string; department?: string }) => {
  setLoading(true);
  try {
    // Build query parameters
    const params: Record<string, string> = {
      page: page.toString(),
      pageSize: pageSize.toString()
    };
    
    // Add filter parameters
    if (filters) {
      if (filters.className && filters.className.trim()) {
        params.className = filters.className.trim();
      }
      if (filters.department && filters.department.trim()) {
        params.department = filters.department.trim();
      }
    }
    
    const queryString = new URLSearchParams(params).toString();
    console.log('Request URL:', `/api/classes?${queryString}`);
    
    const response = await fetch(`/api/classes?${queryString}`);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const result = await response.json();
    console.log('API response data:', result);
    
    // 处理返回数据
    if (result && result.data) {
      setClasses(result.data);
      setPagination(result.pagination || {
        current: page,
        pageSize: pageSize,
        total: result.data.length,
        totalPages: Math.ceil(result.data.length / pageSize)
      });
      
      // 更新班级名称列表（用于下拉选择）
      const names = [...new Set(result.data.map((cls: ClassItem) => cls.className).filter(Boolean) as string[])].sort();
      setClassNames(prev => {
        const combined = [...new Set([...prev, ...names])].sort() as string[];
        return combined;
      });
    } else {
      // 如果返回格式不正确，设置为空数组
      setClasses([]);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: 0,
        totalPages: 0
      });
    }
  } catch (error) {
    console.error('获取班级列表失败:', error);
    message.error('获取班级列表失败');
    setClasses([]);
  } finally {
    setLoading(false);
  }
};

  // 获取所有班级名称（用于下拉选择）
  const fetchAllClassNames = async () => {
    try {
      const response = await fetch('/api/classes?page=1&pageSize=1000');
      if (response.ok) {
        const result = await response.json();
        if (result && result.data) {
          const names = [...new Set(result.data.map((cls: ClassItem) => cls.className).filter(Boolean) as string[])].sort();
          console.log('获取到的班级名称列表:', names);
          setClassNames(names);
        } else {
          console.warn('获取班级名称列表：返回数据格式不正确');
        }
      } else {
        console.error('获取班级名称列表失败，状态码:', response.status);
      }
    } catch (error) {
      console.error('获取班级名称列表失败:', error);
    }
  };

  // 获取统计信息
  const fetchStats = async () => {
    try {
      const response = await fetch('/api/classes/stats/overview');
      if (response.ok) {
        const result = await response.json();
        setStats(result);
      }
    } catch (error) {
      console.error('获取统计信息失败:', error);
    }
  };

  // 初始化：获取选项和统计信息
  useEffect(() => {
    fetchStats();
    fetchOptions();
    fetchAllClassNames();
  }, []);

  // 从URL读取查询参数并自动筛选，确保只显示点击的班级
  useEffect(() => {
    const classNameParam = searchParams.get('className');
    
    if (classNameParam) {
      // 设置筛选条件，只显示该班级
      const newFilters = {
        className: classNameParam,
        department: '' // 只按班级名称筛选，不限制学院
      };
      setSearchFilters(newFilters);
      // 重置分页到第一页
      setPagination(prev => ({
        ...prev,
        current: 1
      }));
      // 加载该班级的数据（只显示这一个班级）
      fetchClasses(1, pagination.pageSize, newFilters);
    } else if (!urlParamsInitialized.current) {
      // 没有URL参数时，正常加载所有班级（仅在首次加载时）
      fetchClasses(1, pagination.pageSize, {});
      urlParamsInitialized.current = true;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchParams]);

  // 处理搜索
  const handleSearch = () => {
    console.log('搜索筛选条件:', searchFilters);
    console.log('班级名称:', searchFilters.className);
    console.log('学院:', searchFilters.department);
    fetchClasses(1, pagination.pageSize, searchFilters);
  };

  // 重置搜索
  const handleReset = () => {
    setSearchFilters({
      className: '',
      department: ''
    });
    fetchClasses(1, pagination.pageSize, {});
  };

  // 处理筛选条件变化
  const handleFilterChange = (field: 'className' | 'department', value: string) => {
    const newFilters = {
      ...searchFilters,
      [field]: value
    };
    setSearchFilters(newFilters);
    // 选择后自动触发搜索
    fetchClasses(1, pagination.pageSize, newFilters);
  };

  // 打开新增模态框（原生实现）
  const handleAdd = () => {
    setEditingClass(null);
    setFormData({
      className: '',
      lecturer: '',
      counselor: '',
      department: '',
      classroom: ''
    });
    setFormErrors({});
    setModalVisible(true);
  };

  // 关闭模态框
  const handleCloseModal = () => {
    setModalVisible(false);
    setEditingClass(null);
    setFormErrors({});
  };

  // 处理表单字段变化
  const handleFormChange = (field: keyof ClassFormData, value: string | number) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // 清除该字段的错误
    if (formErrors[field]) {
      setFormErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  // 验证表单
  const validateForm = (): boolean => {
    const errors: Partial<Record<keyof ClassFormData, string>> = {};
    
    if (!formData.className || formData.className.trim() === '') {
      errors.className = t('pleaseInputClassName');
    }
    
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 处理表单提交（添加和编辑共用）
  const handleFormSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }
    
    try {
      const url = editingClass ? `/api/classes/${editingClass.id}` : '/api/classes';
      const method = editingClass ? 'PUT' : 'POST';
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
      });
      
      if (response.ok) {
        message.success(editingClass ? '更新成功' : '创建成功');
        setModalVisible(false);
        setEditingClass(null);
        fetchClasses(pagination.current, pagination.pageSize, searchFilters);
        fetchStats();
        fetchOptions();
        // 重置表单
        setFormData({
          className: '',
          lecturer: '',
          counselor: '',
          department: '',
          classroom: ''
        });
      } else {
        const result = await response.json();
        message.error(result.error || '操作失败');
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败');
    }
  };

  // 打开编辑模态框
  const handleEdit = (record: ClassItem) => {
    setEditingClass(record);
    setFormData({
      className: record.className || '',
      lecturer: record.lecturer || '',
      counselor: record.counselor || '',
      department: record.department || '',
      classroom: record.classroom || ''
    });
    setFormErrors({});
    setModalVisible(true);
  };

  // 查看班级学生
  const handleViewStudents = async (classItem: ClassItem) => {
    setIsLoadingStudents(true);
    setIsStudentsModalVisible(true);
    setSelectedClassName(classItem.className);
    setSelectedDepartment(classItem.department);
    setSelectedCounselor(classItem.counselor || '');
    setSelectedLecturer(classItem.lecturer || '');
    setSelectedClassroom(classItem.classroom || '');
    setSelectedClassStudents([]);
    
    try {
      // 根据班级名称和学院获取学生数据
      const params = new URLSearchParams({
        className: classItem.className,
        college: classItem.department,
        page: '1',
        pageSize: '1000' // 获取所有学生，不分页
      });
      
      const response = await fetch(`/api/students?${params.toString()}`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      setSelectedClassStudents(result.data || []);
    } catch (error) {
      console.error('获取学生数据失败:', error);
      message.error('获取学生数据失败');
      setSelectedClassStudents([]);
    } finally {
      setIsLoadingStudents(false);
    }
  };

  // 处理删除
  const handleDelete = async (id: number, className: string) => {
    const isConfirmed = window.confirm(`确定要删除班级 "${className}" 吗？此操作不可撤销！`);
    
    if (!isConfirmed) {
      return;
    }

    try {
      const response = await fetch(`/api/classes/${id}`, {
        method: 'DELETE'
      });
      
      const result = await response.json();
      
      if (response.ok) {
        message.success(result.message || '删除成功');
        fetchClasses(pagination.current, pagination.pageSize, searchFilters);
        fetchStats();
      } else {
        // 显示后端返回的具体错误信息
        const errorMessage = result.error || result.message || '删除失败';
        message.error(errorMessage);
        console.error('删除失败:', {
          status: response.status,
          error: errorMessage,
          response: result
        });
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败：网络错误或服务器无响应');
    }
  };


  // 表格列定义
  const columns = [
    {
      title: t('className'),
      dataIndex: 'className',
      key: 'className',
      width: 200,
    },
    {
      title: t('lecturer'),
      dataIndex: 'lecturer',
      key: 'lecturer',
      width: 150,
      render: (lecturer: string) => lecturer || <span style={{ color: '#999' }}>{t('common:notSet')}</span>
    },
    {
      title: t('counselor'),
      dataIndex: 'counselor',
      key: 'counselor',
      width: 150,
      render: (counselor: string) => counselor || <span style={{ color: '#999' }}>{t('common:notSet')}</span>
    },
    {
      title: t('department'),
      dataIndex: 'department',
      key: 'department',
      width: 150,
      render: (department: string) => department || <span style={{ color: '#999' }}>{t('common:notSet')}</span>
    },
    {
      title: '教室号',
      dataIndex: 'classroom',
      key: 'classroom',
      width: 120,
      render: (classroom: string) => classroom || <span style={{ color: '#999' }}>{t('common:notSet')}</span>
    },
    {
      title: t('common:operation'),
      key: 'actions',
      width: 180,
      render: (_: unknown, record: ClassItem) => (
        <Space size="small" onClick={(e) => e.stopPropagation()}>
          <Tooltip title={t('viewStudents')}>
            <Button
              type="link"
              icon={<EyeOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                handleViewStudents(record);
              }}
            />
          </Tooltip>
          <Tooltip title={t('common:edit')}>
            <Button
              type="link"
              icon={<EditOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                handleEdit(record);
              }}
            />
          </Tooltip>
          <Tooltip title={t('common:delete')}>
            <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />}
              onClick={(e) => {
                e.stopPropagation();
                handleDelete(record.id, record.className);
              }}
            />
          </Tooltip>
        </Space>
      )
    }
  ];

  return (
    <div className={styles.classManagement}>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title={t('totalClasses')}
              value={stats.totalClasses}
              prefix={<TeamOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title={t('totalStudents')}
              value={stats.totalStudents}
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title={t('activeClasses')}
              value={stats.activeClasses}
              suffix={`/ ${stats.totalClasses}`}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title={t('averageStudents')}
              value={stats.averageStudents}
              suffix={t('personPerClass')}
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索和操作栏 */}
      <Card
        title={t('title')}
        extra={
          <button className={styles.addButton} onClick={handleAdd}>
            <PlusOutlined /> {t('addClass')}
          </button>
        }
        style={{ marginBottom: 16 }}
      >
        <Space size="middle" style={{ marginBottom: 16 }} wrap>
          <select
            value={searchFilters.className}
            onChange={(e) => handleFilterChange('className', e.target.value)}
            style={{ 
              padding: '8px 12px', 
              border: '1px solid #d9d9d9', 
              borderRadius: '4px',
              minWidth: '200px',
              fontSize: '14px'
            }}
          >
            <option value="">请选择班级名称</option>
            {classNames.map(name => (
              <option key={name} value={name}>{name}</option>
            ))}
          </select>
          <select
            value={searchFilters.department}
            onChange={(e) => handleFilterChange('department', e.target.value)}
            style={{ 
              padding: '8px 12px', 
              border: '1px solid #d9d9d9', 
              borderRadius: '4px',
              minWidth: '200px',
              fontSize: '14px'
            }}
          >
            <option value="">请选择学院</option>
            {options.departments.map(dept => (
              <option key={dept} value={dept}>{dept}</option>
            ))}
          </select>
          <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
            {t('common:search')}
          </Button>
          <Button icon={<ReloadOutlined />} onClick={handleReset}>
            {t('common:reset')}
          </Button>
        </Space>

        {/* 班级表格 */}
        <Table
          columns={columns}
          dataSource={classes}
          rowKey="id"
          loading={loading}
          onRow={(record) => ({
            onClick: () => {
              // 跳转到学生管理页面，传递班级名称和学院参数进行筛选
              const params = new URLSearchParams({
                className: record.className,
                college: record.department
              });
              navigate(`/admin/students?${params.toString()}`);
            },
            style: { cursor: 'pointer' }
          })}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              const newPageSize = pageSize || pagination.pageSize;
              setPagination(prev => ({ 
                ...prev, 
                current: page, 
                pageSize: newPageSize 
              }));
              fetchClasses(page, newPageSize, searchFilters);
            }
          }}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 原生模态框（添加和编辑共用） */}
      {modalVisible && (
        <div className={styles.modalOverlay} onClick={handleCloseModal}>
          <div className={styles.modal} onClick={(e) => e.stopPropagation()}>
            <div className={styles.modalHeader}>
              <h3>
                {editingClass ? (
                  <>
                    <EditOutlined /> {t('editClass')}
                  </>
                ) : (
                  <>
                    <PlusOutlined /> {t('addClass')}
                  </>
                )}
              </h3>
              <button className={styles.closeBtn} onClick={handleCloseModal}>
                <CloseOutlined />
              </button>
            </div>
            
            <form className={styles.formContainer} onSubmit={handleFormSubmit}>
              <div className={styles.formRow}>
                <div className={`${styles.formGroup} ${styles.required}`}>
                  <label>{t('className')}</label>
                  <input
                    type="text"
                    value={formData.className}
                    onChange={(e) => handleFormChange('className', e.target.value)}
                    placeholder="例如：计算机科学与技术1班"
                    className={formErrors.className ? styles.error : ''}
                  />
                  {formErrors.className && (
                    <span className={styles.errorText}>{formErrors.className}</span>
                  )}
                </div>
              </div>

              <div className={styles.formRow}>
                <div className={styles.formGroup}>
                  <label>{t('lecturer')}</label>
                  <select
                    value={formData.lecturer}
                    onChange={(e) => handleFormChange('lecturer', e.target.value)}
                  >
                    <option value="">{t('pleaseSelectLecturer')}</option>
                    {options.lecturers.length > 0 ? (
                      options.lecturers.map(lecturer => (
                        <option key={lecturer} value={lecturer}>{lecturer}</option>
                      ))
                    ) : (
                      <option value="" disabled>暂无讲师数据</option>
                    )}
                  </select>
                  {options.lecturers.length === 0 && (
                    <span style={{ color: '#ff4d4f', fontSize: '12px' }}>
                      警告：未获取到讲师数据，请刷新页面或检查后端服务
                    </span>
                  )}
                </div>
                <div className={styles.formGroup}>
                  <label>{t('counselor')}</label>
                  <select
                    value={formData.counselor}
                    onChange={(e) => handleFormChange('counselor', e.target.value)}
                  >
                    <option value="">{t('pleaseSelectCounselor')}</option>
                    {options.counselors.length > 0 ? (
                      options.counselors.map(counselor => (
                        <option key={counselor} value={counselor}>{counselor}</option>
                      ))
                    ) : (
                      <option value="" disabled>暂无导员数据</option>
                    )}
                  </select>
                </div>
              </div>

              <div className={styles.formRow}>
                <div className={styles.formGroup}>
                  <label>{t('department')}</label>
                  <select
                    value={formData.department}
                    onChange={(e) => handleFormChange('department', e.target.value)}
                  >
                    <option value="">{t('pleaseSelectCollege')}</option>
                    {options.departments.length > 0 ? (
                      options.departments.map(department => (
                        <option key={department} value={department}>{department}</option>
                      ))
                    ) : (
                      <option value="" disabled>暂无学院数据</option>
                    )}
                  </select>
                  {options.departments.length === 0 && (
                    <span style={{ color: '#ff4d4f', fontSize: '12px' }}>
                      警告：未获取到学院数据，请刷新页面或检查后端服务
                    </span>
                  )}
                </div>
                <div className={styles.formGroup}>
                  <label>教室号</label>
                  <input
                    type="text"
                    value={formData.classroom || ''}
                    onChange={(e) => handleFormChange('classroom', e.target.value)}
                    placeholder="请输入教室号，例如：704"
                  />
                </div>
              </div>

              <div className={styles.modalActions}>
                <button type="button" className={styles.btnCancel} onClick={handleCloseModal}>
                  {t('common:cancel')}
                </button>
                <button type="submit" className={styles.btnPrimary}>
                  {editingClass ? t('common:update') : t('common:create')}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* 学生列表模态框 */}
      {isStudentsModalVisible && (
        <div className={styles.modalOverlay} onClick={() => setIsStudentsModalVisible(false)}>
          <div className={styles.modal} onClick={(e) => e.stopPropagation()} style={{ maxWidth: '900px', width: '90%' }}>
            <div className={styles.modalHeader}>
              <div style={{ flex: 1 }}>
                <h3>{t('classStudents')} - {selectedClassName}</h3>
                <div style={{ display: 'flex', gap: '1.5rem', marginTop: '0.5rem', fontSize: '0.875rem', color: '#64748b', flexWrap: 'wrap' }}>
                  {selectedCounselor && (
                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                      <span style={{ fontWeight: 600, color: '#374151' }}>{t('counselor')}:</span>
                      <span>{selectedCounselor}</span>
                    </div>
                  )}
                  {selectedLecturer && (
                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                      <span style={{ fontWeight: 600, color: '#374151' }}>{t('lecturer')}:</span>
                      <span>{selectedLecturer}</span>
                    </div>
                  )}
                  {selectedClassroom && (
                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                      <span style={{ fontWeight: 600, color: '#374151' }}>{t('classroom')}:</span>
                      <span>{selectedClassroom}</span>
                    </div>
                  )}
                  {selectedDepartment && (
                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                      <span style={{ fontWeight: 600, color: '#374151' }}>{t('department')}:</span>
                      <span>{selectedDepartment}</span>
                    </div>
                  )}
                </div>
              </div>
              <button className={styles.closeBtn} onClick={() => setIsStudentsModalVisible(false)}>
                <CloseOutlined />
              </button>
            </div>
            <div style={{ padding: '1.5rem', maxHeight: '70vh', overflowY: 'auto' }}>
              {isLoadingStudents ? (
                <div style={{ textAlign: 'center', padding: '2rem' }}>加载中...</div>
              ) : selectedClassStudents.length > 0 ? (
                <div className={styles.studentsTable}>
                  <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                    <thead>
                      <tr>
                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid #e5e7eb', background: '#f8fafc', fontWeight: 600 }}>{tStudent('studentId')}</th>
                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid #e5e7eb', background: '#f8fafc', fontWeight: 600 }}>{tStudent('name')}</th>
                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid #e5e7eb', background: '#f8fafc', fontWeight: 600 }}>{tStudent('gender')}</th>
                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid #e5e7eb', background: '#f8fafc', fontWeight: 600 }}>{tStudent('phone')}</th>
                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid #e5e7eb', background: '#f8fafc', fontWeight: 600 }}>{tStudent('college')}</th>
                        <th style={{ padding: '0.75rem', textAlign: 'left', borderBottom: '1px solid #e5e7eb', background: '#f8fafc', fontWeight: 600 }}>{tStudent('status')}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {selectedClassStudents.map((student) => (
                        <tr key={student.id} style={{ borderBottom: '1px solid #e5e7eb' }}>
                          <td style={{ padding: '0.75rem' }}>{student.studentId}</td>
                          <td style={{ padding: '0.75rem', fontWeight: 500 }}>{student.name}</td>
                          <td style={{ padding: '0.75rem' }}>{student.gender || '-'}</td>
                          <td style={{ padding: '0.75rem' }}>{student.phone || '-'}</td>
                          <td style={{ padding: '0.75rem' }}>{student.college || student.className || '-'}</td>
                          <td style={{ padding: '0.75rem' }}>
                            <span style={{
                              padding: '0.25rem 0.75rem',
                              borderRadius: '12px',
                              fontSize: '0.875rem',
                              fontWeight: 500,
                              background: student.status === 'active' ? '#d1fae5' : student.status === 'suspended' ? '#fee2e2' : '#e0e7ff',
                              color: student.status === 'active' ? '#065f46' : student.status === 'suspended' ? '#991b1b' : '#3730a3'
                            }}>
                              {student.status === 'active' ? tStudent('active') : student.status === 'suspended' ? tStudent('onLeave') : student.status === 'graduated' ? tStudent('graduated') : student.status || '-'}
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div style={{ textAlign: 'center', padding: '2rem', color: '#64748b' }}>
                  {t('noStudents')}
                </div>
              )}
            </div>
            <div className={styles.modalActions}>
              <button type="button" className={styles.btnCancel} onClick={() => setIsStudentsModalVisible(false)}>
                关闭
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ClassManagement;